package swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * 登录对话框演示
 * @author fidel
 */
public class LoginDialogDemo extends JDialog {
    private static final long serialVersionUID = 6029939734925194360L;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton buttonOkey;
    private JButton buttonReset;

    public static void main(String[] args) {
        JDialog dialog = new LoginDialogDemo();
        dialog.setVisible(true);
    }

    private LoginDialogDemo() {
        setTitle("登录");
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setSize(250, 150);
        setLocationRelativeTo(null);
        JPanel textPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        getContentPane().add(textPanel, BorderLayout.NORTH);
        textPanel.setLayout(new GridLayout(2, 2));
        textPanel.add(new JLabel("用户名称"));
        usernameField = new JTextField();
        textPanel.add(usernameField);
        textPanel.add(new JLabel("用户密码"));
        passwordField = new JPasswordField();
        textPanel.add(passwordField);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        buttonOkey = new JButton("登录");
        buttonReset = new JButton("重置");
        buttonOkey.addActionListener(listener());
        buttonReset.addActionListener(listener());
        buttonPanel.add(buttonOkey);
        buttonPanel.add(buttonReset);
    }

    private ActionListener listener() {
        return e -> {
            if (e.getSource() == buttonOkey) {
                char[] chars = passwordField.getPassword();
                StringBuilder password = new StringBuilder();
                for (char aChar : chars) {
                    password.append(aChar);
                }
                if ("java".equals(usernameField.getText()) && "swing".equals(password.toString())) {
                    JOptionPane.showMessageDialog(null, "登录成功");
                    System.exit(WindowEvent.WINDOW_CLOSING);
                } else {
                    JOptionPane.showMessageDialog(null, "登录失败");
                }
            } else if (e.getSource() == buttonReset) {
                if (JOptionPane.showConfirmDialog(null, "确定重置所有字段吗？", "重置", JOptionPane.YES_NO_OPTION) == 0) {
                    usernameField.setText(null);
                    passwordField.setText(null);
                }
            }
        };
    }
}
